package com.project.demo.service;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.demo.dao.CodeHistoryMapper;
import com.project.demo.dao.UserMapper;
import com.project.demo.dao.base.BaseMapper;
import com.project.demo.entity.CodeHistory;
import com.project.demo.entity.CodeHistoryDto;
import com.project.demo.entity.Result;
import com.project.demo.entity.User;
import com.project.demo.enums.ResultCode;
import com.project.demo.service.base.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CodeHistoryServie extends BaseService<CodeHistory> {

	@Autowired
	CodeHistoryMapper codeHistoryMapper;

	@Autowired
	UserMapper userMapper;

	@Autowired
	private BaseMapper baseMapper;
	public Result<Object> saveCodeHistory(CodeHistoryDto codeHistoryDto) {
		CodeHistory codeHistory = new CodeHistory();
		BeanUtils.copyProperties(codeHistoryDto, codeHistory);
		codeHistory.setUserId(String.valueOf(codeHistoryDto.getUserId()));
		codeHistory.setClassx(String.valueOf(codeHistoryDto.getClassX()));
		codeHistory.setClassx(String.valueOf(codeHistoryDto.getClassX()));
		codeHistory.setExamId(String.valueOf(codeHistoryDto.getExamId()));
		this.save(codeHistory);
		return new Result<>(ResultCode.C200);
	}

	public Map<String, Object> listCodeHistory(Integer page, Integer size, Integer conn_user) {

		Map<String, Object> map = new HashMap<>();

		LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
		userLambdaQueryWrapper.eq(User::getConnUser, conn_user);
		List<Integer> collect = userMapper.selectList(userLambdaQueryWrapper).stream().map(User::getUserId).collect(Collectors.toList());

		if (CollectionUtil.isEmpty(collect)) {
			return map;
		}

		LambdaQueryWrapper<CodeHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.in(CodeHistory::getUserId, collect)
				.in(CodeHistory::getCodeColor, "red", "yellow");


		Page<CodeHistory> ipage = new Page<>(page, size);

		IPage<CodeHistory> codeHistoryIPage = codeHistoryMapper.selectPage(ipage, lambdaQueryWrapper);


		map.put("list", codeHistoryIPage.getRecords());
		map.put("count", codeHistoryIPage.getTotal());
		return map;

	}
}
